<?php	namespace Admin\Controller;
class CategoryController extends CommonController
{
	
	
	protected $db;
	//构造方法
	public function __init()
	{
		//实例化Category模型
		$this->db = new \Common\Model\Category;
	}
	//分类首页
	public function index()
	{
		//排序显示所有数据
		$data = $this->db->orderBy("csort","ASC") ->get();
		$data = Data::tree($data,"cname");
//		p($data);
		View::with("data",$data);
		View::make();
	}
	//添加分类
	public function add()
	{
		if(IS_AJAX)
		{
			if(!$this->db->store())
			{
				View::ajax(array('status'=>0,'message'=>$this->db->getError()));
			}else{
				View::ajax(array('status'=>1,'message'=>"添加成功"));
			}
		}
		View::make();
	}
	//添加子分类
	public function addSon()
	{
		if(IS_AJAX)
		{
			if(!$this->db->store())
			{
				View::ajax(array('status'=>0,'message'=>$this->db->getError()));
			}else{
				View::ajax(array('status'=>1,'message'=>"添加成功"));
			}
		}
		$cid = Q("get.cid",0,'intval');
//		p($cid);
		$cateData = $this ->db ->where('cid',$cid)->field("cid,cname")->first();
//		p($cateData);
		View::with("cateData",$cateData);
		View::make();
	}
	//编辑分类
	public function edit()
	{
		if(IS_AJAX)
		{
			if(!$this->db->edit())
			{
				View::ajax(array('status'=>0,'message'=>$this->db->getError()));
			}else
			{
				View::ajax(array('status'=>1,'message'=>"编辑成功"));	
			}			
		}
		$cid = Q("get.cid",0,"intval");
//		p($cid);
		$oldData = $this->db->where('cid',$cid)->first();
//		p($oldData);
		View::with('oldData',$oldData);
		//处理所属分类
		$cateData = $this->db->getCataData($cid);
//		p($cateData);
		//分配数据
		View::with('cateData',$cateData);
		View::make();
	}
	public function del()
	{
		$cid = Q('get.cid',0,'intval');
//		echo $cid;
		$this->db->del($cid);
		$this -> success("删除成功",U("index"));
	}
}
